<template>
  <base-modal
    :title="(action === 'update'?$t('common.base.edit'):$t('common.base.add'))+$t('common.base.qualification')"
    :show.sync="remindCustomerDialog"
    class="batch-remind-customer-dialog"
    @closed="closeDialog"
    style="z-index:1001"
  >
    <el-form
      :model="form"
      ref="form"
      label-position="top"
      
      class="demo-ruleForm service_form"
      style="padding: 20px;"
      :rules="rules"
    >
      <!-- <el-form-item :label="$t('common.label.qualificationName')" prop="qualificationName">
        <el-input
          v-model="form.qualificationName"
          :placeholder="$t('common.placeholder.inputQualificationName')"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('common.base.firstReviewTime')">
        <el-date-picker
          v-model="form.preliminaryExaminationTime"
          value-format="timestamp"
          :placeholder="$t('common.placeholder.selectFirstReviewTime')"
          type="date"
        ></el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('common.base.secondReviewTime')">
        <el-date-picker
          v-model="form.reviewTime"
          value-format="timestamp"
          :placeholder="$t('common.placeholder.selectReviewTime')"
          type="date"
        ></el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('common.base.endTime_1')" prop="expireTime">
        <el-date-picker
          v-model="form.expireTime"
          value-format="timestamp"
          :placeholder="$t('common.placeholder.selectEndTime_1')"
          type="date"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('common.label.qualicationAttachment')" prop="enclosures">
        <base-upload
          :value="form.enclosures"
          @input="enclosuresUpload"
          @remove="enclosuresRemove"
        ></base-upload>
      </el-form-item> -->
      <template>
        <el-form-item v-if="!form.id" :label="$t('common.label.qualificationName')" prop="qualification">
          <biz-remote-select v-model="form.qualification" :placeholder="$t('common.placeholder.select')" :input-disabled="form.id" :remote-method="toGetListQualificationManagement" :cleared="true" @input="computedEndTime"/>
        </el-form-item>
        <el-form-item v-else :label="$t('common.label.qualificationName')" prop="qualificationName">
          <div class="overHideCon-1">{{form.qualificationName}}</div>
        </el-form-item>
        
        <el-form-item :label="$t('qualificationManagement.field.startTime.displayName')" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            value-format="timestamp"
            :placeholder="$t('common.placeholder.select')"
            @change="computedEndTime"
            type="date"
          ></el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('qualificationManagement.field.endTime.displayName')" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            value-format="timestamp"
            :placeholder="$t('common.placeholder.select')"
            type="date"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('qualificationManagement.field.certificate.displayName')" prop="attachments">
          <base-upload
            :value="form.attachments"
            @input="enclosuresUpload"
            @remove="enclosuresRemove"
          ></base-upload>
        </el-form-item>
      </template>
      <template>
        <el-form-item :label="$t('common.label.expireRemind')">
          <el-switch
            :active-value="true" 
            :inactive-value="false"
            v-model="form.openRemind"
          ></el-switch>
        </el-form-item>
        <template v-if="form.openRemind">
          <el-form-item label="" prop="remindAdvance">
            <i18n path="serviceProvider.endTimeAlert" tag="span">
              <el-input-number place="time" :min="0" :max="999999" v-model="form.remindAdvance" :controls="false"></el-input-number>
            </i18n>
          </el-form-item>
          <el-form-item label="" prop="remindUsers">
            {{$t('serviceProvider.selectAlertMember')}}
            <form-user
              :field="userIds"
              v-model="form.remindUsers"
              max="10"
              multiple
            />
          </el-form-item>
        </template>
      </template>
    </el-form>
  
    
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">{{$t('common.base.close')}}</el-button>
      <el-button type="primary" @click="submit">{{$t('common.base.save')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
import _, { cloneDeep } from 'lodash';
import { t } from '@src/locales'
import { getListQualificationManagement } from '@src/api/UserCenterApi'
// 大于等于0小于等于999999的整数
const numberReg3 = /^([0-9][0-9]{0,5}|999999)$/

export default {
  name: 'zi-zhi-from',
  data: () => {
    return {
      action:'',
      remindCustomerDialog: false,
      pending: false,
      editedRemind: {},
      list: [],
      userIds: {
        displayName: t('common.base.person'),
        fieldName: 'userIds',
        formType: 'user',
        isNull: 0,
      },
      form:{
        attachments: [], // 技能证书
        qualificationName: '',
        remindAdvance: 30,
        remindUsers: [],
        openRemind: false,
        preliminaryExaminationTime: '',
        startTime: null,
        endTime: null,
        qualification:[]
      },
      
      pickerOptions: { 
        //  disabledDate(time) {
        //     return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的 
        //  }
  	  }
    };
  },
  computed:{
    isEditPage(){
      return !!this.form.id
    },
    rules(){
      return {
        qualification: [{ required: true, message: t('common.placeholder.selectSomething', {0:t('common.label.qualificationName')}), trigger: 'change' }, { validator: (rule, value, callback) => {
          if (value && !value.length) {
            callback(new Error(t('common.placeholder.selectSomething', {0:t('common.label.qualificationName')})));
          } else {
            callback();
          }
        }, trigger: 'blur' }],
        remindAdvance: [{ required: true, message: t('common.placeholder.inputDays'), trigger: 'change' }, {
          validator: (rule, value, callback) => {
          if (!numberReg3.test(value)) {
            callback(new Error(t(`${t('common.placeholder.input2')}0~999999 ${t('common.validate.onlyInputInt')}`)));
          } else {
            callback();
          }
        }, trigger: 'input'
        }],
        remindUsers: [{ required: true, message: t('common.placeholder.selectMember'), trigger: 'change' }],
        endTime:[{ required: false, validator: (rule, value, callback) => {
          if (value && this.form.startTime && value * 1 < this.form.startTime * 1) {
            callback(new Error(t('qualificationManagement.field.endTime.tips')));
          } else {
            callback();
          }
        }, trigger: 'change' }],
      }
    },
  },
  mounted() {
  },
  watch: {
    'form.remindUsers':{
      handler(newValue){
        if(newValue){
          this.$nextTick(() => this.$refs.form.clearValidate());
        }
      }
    },
    'form.openRemind':{
      handler(newValue){
        if(newValue == 1){
          this.$set(this.rules, 'expireTime', [{ required: true, message: this.$t('common.placeholder.selectEndTime'), trigger: 'change' }])
        }else{
          this.$set(this.rules, 'expireTime', [])
        }
        this.$nextTick(() => this.$refs.form.clearValidate());
      }
    }
  },
  methods: {
    async submit(){
      try {
        const validateRes = await this.$refs.form.validate();
        if (!validateRes) return;
        this.action === 'update' ? this.$emit('updateQualifications', this.form) : this.$emit('addQualifications', this.form) 
      } catch (e) {
        console.error('err', e);
      }
    },
    // 移除上传
    async enclosuresRemove(file) {
      if (!(await this.$platform.confirm(this.$t('common.form.preview.file.deleteFileTips')))) return;

      let index = -1;
      for (let i = 0; i < this.form.attachments.length; i++) {
        let f = this.form.attachments[i];
        if (f.url == file.url) {
          index = i;
          break;
        }
      }
      if (index >= 0) this.form.attachments.splice(index, 1);
      this.$forceUpdate();
    },
    // 上传
    enclosuresUpload(queue) {
      this.$set(this.form, 'attachments', queue);
      this.$forceUpdate();
      this.$nextTick(() => this.$refs.form.clearValidate());
    },
    openDialog(action, data) {
      if(action === 'update' || action === 'note'){
        const formData = cloneDeep(data)
        this.action = 'update'
        this.form.qualificationName = formData.qualificationName
        this.form.attachments = formData.attachments || []
        this.form.remindAdvance = formData.remindAdvance
        this.form.remindUsers = formData.remindUsers
        this.form.openRemind = formData.openRemind
        this.form.startTime = formData.startTime || null
        this.form.endTime = formData.endTime || null
        this.form.id = formData.id
      }else{
        this.action = 'create'
        this.form = {
          attachments: [], // 技能证书
          qualificationName: '',
          remindAdvance: 30,
          remindUsers: [],
          openRemind: false,
          // preliminaryExaminationTime: '',
          // reviewTime: '',
          // expireTime: '',
          qualification:[],
          startTime:null,
          endTime:null
        }
        this.$nextTick(() => this.$refs.form.clearValidate());
      }
      this.remindCustomerDialog = true;
    },
    closeDialog(){
      this.remindCustomerDialog = false;
    },
    toGetListQualificationManagement(params){
      return getListQualificationManagement(params).then(res=>{
        if(res.status === 0 ){
          return {
            ...res.data,
            list:res.data.list.map(item=>{
              return {
                label:item.qualificationName,
                value:item.id,
                time:item.effectiveTime
              }
            })
          }
        }
      })
    },
    computedEndTime(){
      this.$nextTick(()=>{
        let time = this.isEditPage ? this.form.effectiveTime : this.form.qualification?.[0]?.time || null
        let startTime = this.form.startTime
        if(time && startTime){
          this.form.endTime = startTime * 1 + ((time * 1) * 24 * 60 * 60 - 1) * 1000
        }
      })
      
    }
  },
};
</script>

<style lang="scss">

</style>
